import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:get/get.dart';
import 'package:namewava/utils/jc_global.dart';
import 'package:namewava/utils/jc_image_path.dart';
import 'package:namewava/utils/jc_nav.dart';
import 'package:namewava/utils/jc_purchase.dart';
import 'package:namewava/utils/jc_screenutil_info.dart';
import 'package:namewava/utils/jc_text_style.dart';
import 'package:namewava/utils/js_request.dart';
import 'package:notification_centre/notification_centre.dart';

class JcAppPurchase extends StatefulWidget {
  const JcAppPurchase({super.key});

  @override
  State<JcAppPurchase> createState() => _JcAppPurchaseState();
}

class _JcAppPurchaseState extends State<JcAppPurchase> {
  RxBool isFinshed = false.obs;
  RxInt myCoins = 0.obs;
  List purchaseData = [];

  String? orderNo;

  final JcPurchase _jcPurchase = JcPurchase();
  _wavaUserInfo() {
    JsRequest.getWavaUserInfo(success: (res) {
      JsRequest.getPurchaseList(success: (res1) {
        purchaseData = res1;
        myCoins.value = res['availableCoins'];
        isFinshed.value = true;
      });
    });
  }

  @override
  void initState() {
    super.initState();
    _jcPurchase.initializeInAppPurchase();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _wavaUserInfo();
    });

    ///充值成功验单
    NotificationCenter().addObserver('appPurchaseSuccess', this, (res) {
      if (mounted) {
        _checkBuyCoins(res);
      }
    });
  }

  @override
  void dispose() {
    NotificationCenter().removeObserver('appPurchaseSuccess', this);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        height: JcScreenutilInfo.screenHeight,
        decoration: const BoxDecoration(
            image: DecorationImage(
                image: AssetImage(JcImagePath.jcMinePageBg), fit: BoxFit.fill)),
        child: Column(
          children: [
            JcNav(
              title: 'Coin Shop',
              backFunction: () {
                Get.back();
              },
            ),
            Obx(() {
              return isFinshed.value
                  ? _contentWidget()
                  : const SizedBox(
                      height: 0,
                    );
            })
          ],
        ),
      ),
    );
  }

  _contentWidget() {
    return Expanded(
        child: Column(
      children: [_myicons(), _purchase()],
    ));
  }

  _myicons() {
    return Container(
      height: 160.h,
      width: double.infinity,
      margin: EdgeInsets.only(left: 20.w, right: 20.w, top: 50.h),
      decoration: const BoxDecoration(
          image: DecorationImage(
              image: AssetImage(JcImagePath.jcWavaPurchaseBg),
              fit: BoxFit.fill)),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset(
            JcImagePath.jcWavaPurchaseIcon,
            width: 50.w,
            height: 50.w,
          ),
          // SizedBox(
          //   height: 5.h,
          // ),
          Text(
            myCoins.value.toString(),
            style:
                JcTextStyle.sourceKeynoteartHansTextStyle(20.sp, Colors.white),
          ),
          // SizedBox(
          //   height: 5.h,
          // ),
          Text(
            'My Coins',
            style:
                JcTextStyle.sourceKeynoteartHansTextStyle(20.sp, Colors.white),
          ),
        ],
      ),
    );
  }

  _purchase() {
    return Expanded(
        child: Container(
      margin: EdgeInsets.only(
          right: 20.w, bottom: JcScreenutilInfo.bottomBarHeight + 10.h),
      color: Colors.transparent,
      child: MasonryGridView.count(
        shrinkWrap: true,
        //  physics: const NeverScrollableScrollPhysics(),
        padding: EdgeInsets.zero,
        crossAxisCount: 2,
        itemCount: purchaseData.length,
        itemBuilder: (BuildContext context, int index) {
          Map dic = purchaseData[index];
          var discount = dic['discount'] ?? 0;
          String tags = dic['tags'] ?? '';
          return GestureDetector(
            child: Stack(
              children: [
                Container(
                  margin: EdgeInsets.only(top: 30.h, left: 20.w),
                  width: 0.5 * (JcScreenutilInfo.screenWidth - 60.w),
                  height: 0.5 * (JcScreenutilInfo.screenWidth - 60.w),
                  decoration: BoxDecoration(
                      color: const Color(0xFFDCE9FF),
                      borderRadius: BorderRadius.circular(10.r)),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      SizedBox(
                        width: double.infinity,
                        height: 50.w,
                        child: Row(
                          children: [
                            Expanded(
                                flex: 1,
                                child: Container(
                                  // color: Colors.red,
                                  alignment: Alignment.centerRight,
                                  child: Image.asset(
                                    JcImagePath.jcWavaPurchaseIcon,
                                    width: 50.w,
                                    height: 50.w,
                                  ),
                                )),
                            Expanded(
                                flex: 1,
                                child: Container(
                                  padding: EdgeInsets.only(left: 5.w),
                                  height: 50.w,
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Text(
                                        dic['exchangeCoin'].toString(),
                                        style: JcTextStyle
                                            .octoberDevanagariMediumTextStyle(
                                                19.sp, Colors.black),
                                      ),
                                      discount > 0
                                          ? Text(
                                              '${discount}% off',
                                              style: JcTextStyle
                                                  .octoberDevanagariMediumTextStyle(
                                                      10.sp,
                                                      const Color(0xFF3A79FF)),
                                            )
                                          : const SizedBox(
                                              height: 0,
                                            )
                                    ],
                                  ),
                                ))
                          ],
                        ),
                      ),
                      // SizedBox(
                      //   height: 10.h,
                      // ),
                      SizedBox(
                        height: 20.h,
                        child: Row(
                          children: [
                            Expanded(
                                flex: 1,
                                child: Container(
                                  // color: Colors.red,
                                  alignment: Alignment.centerRight,
                                  child: Text(
                                    "\$" '${dic['price']}',
                                    style: JcTextStyle
                                        .octoberDevanagariMediumTextStyle(
                                            14.sp, Colors.black),
                                  ),
                                )),
                            Expanded(
                                flex: 1,
                                child: Container(
                                    padding: EdgeInsets.only(left: 5.w),
                                    child: discount > 0
                                        ? Text(
                                            "\$" + '${dic['originalPrice']}',
                                            style: JcTextStyle
                                                .octoberDevanagariMediumTextStyle(
                                                    10.sp,
                                                    const Color.fromRGBO(
                                                        0, 0, 0, 0.3),
                                                    decor: TextDecoration
                                                        .lineThrough),
                                          )
                                        : const SizedBox(
                                            width: 0,
                                          )))
                          ],
                        ),
                      )
                    ],
                  ),
                ),
                Positioned(
                  right: 0,
                  top: 16.h,
                  child: tags.contains('Big')
                      ? Image.asset(JcImagePath.jcWavaPurchaseBig)
                      : tags.contains('Hot')
                          ? Image.asset(JcImagePath.jcWavaPurchaseHot)
                          : const SizedBox(
                              width: 0,
                            ),
                )
              ],
            ),
            onTap: () {
              JcGlobal.of(context).logReport({'page': 'createorder'});
              JsRequest.createRechargePurchase(
                  goodsCode: dic['code'],
                  success: (res) {
                    _buyCoins(res);
                  });
            },
          );
        },
      ),
    ));
  }

  _buyCoins(var data) {
    /// lanlin716@802.com  LanlinTest802.
    orderNo = data['orderNo'];
    EasyLoading.show(maskType: EasyLoadingMaskType.black);
    _jcPurchase.buyProduct(data['goodsCode'], data['orderNo']);
  }

  _checkBuyCoins(Map p) {
    p['type'] = 1;
    p['orderNo'] = orderNo;
    JsRequest.rechargeCheck(
        parms: p,
        success: (res) {
          NotificationCenter().postNotification('coinChange');
          _wavaUserInfo();
        });
  }
}
